package com.gionee.survey.controller;

import java.io.IOException;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gionee.survey.bean.Feedback;
import com.gionee.survey.service.IFeedbackService;

/**
 * 问卷反馈控制类
 * @author yuwei
 * @time 2017年4月17日 上午11:12:23
 */
@Controller
@RequestMapping("feedback")
public class FeedBackController {
	@Resource
	private IFeedbackService feedbackService;
	/**
	 * 保存问卷反馈
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("saveFeedback")
	public String saveFeedback(HttpServletResponse response, String obj, String imei) throws IOException{
		String[] feed = obj.split(";");	// 将json数据拆分为单个json feedback对象
		int index = 1;	// 排序
		String customer = UUID.randomUUID().toString().replace("-", "");	// 反馈用户id
		if (imei == null || "".equals(imei)) {
			imei = customer;
		}
		for (int i = 0; i < feed.length; i++) {
			if (feed[i].length() <= 2) {	// 当为空的时候，即"{}"时，跳过
				continue;
			}
			String id = UUID.randomUUID().toString().replace("-", "");	// 反馈id
			JSONObject fd = JSON.parseObject(feed[i]);
			Feedback feedback = new Feedback();
			/*
			 * 设置feedback值
			 */
			feedback.setId(id);
			feedback.setUserId(customer);
			feedback.setImei(imei);
			feedback.setSurveyId(fd.getString("survey_id"));
			feedback.setQuestionNo(fd.getString("question_no"));
			feedback.setQuestionId(fd.getString("question_id"));
			feedback.setQuestionType(fd.getString("question_type"));
			feedback.setAnswer(fd.getString("answer"));
			feedback.setFeedbackSort(index++);
			// 持久化
			feedbackService.insert(feedback);
		}
		String str = JSON.parse("{'success':'success'}").toString();
		response.getWriter().print(str);
		response.getWriter().flush();
		response.getWriter().close();
		return "success";
	}
}
